package com.shop.front.dao.store;


import com.shop.jpa.BaseSQLDao;
import com.shop.jpa.support.QuerySQL;
import com.shop.front.request.store.StoreProductReq;
import com.shop.front.vo.store.StoreProductVo;
import com.shop.web.context.WebContext;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Repository;

@Repository
public class StoreProductSQLDao extends BaseSQLDao {

    public StoreProductVo findVoById(Long id) {
        String field = "sp.*, spc.price pink_price";
        String from = "t_store_product sp left join t_store_pink_config spc on sp.pink_id = spc.id";
        String order = "sp.id desc";

        QuerySQL qs = new QuerySQL(field, from, order);
        qs.addWhereWithoutParams("sp.is_deleted = 0 and sp.is_show = 1");
        qs.addWhereEq("sp.id", id);

        return this.querySingle(qs, StoreProductVo.class);
    }

    public Page<StoreProductVo> page(StoreProductReq req) {
        String field = "sp.*, spc.price pink_price";
        String from = "t_store_product sp left join t_store_pink_config spc on sp.pink_id = spc.id";
        String order = "sp.sort desc, sp.id desc";

        // 排序规则
        if(null != req.getSortId()) {
            if(1 == req.getSortId()) {
                order = "sp.sales desc";
            } else if(2 == req.getSortId()) {
                order = "sp.price desc";
            } else if(3 == req.getSortId()) {
                order = "sp.price asc";
            }
        }

        QuerySQL qs = new QuerySQL(WebContext.getPageNo(), WebContext.getPageSize(), field, from, order);
        qs.addWhereWithoutParams("sp.is_deleted = 0 and sp.is_show = 1");
        qs.addWhereEqNotEmpty("sp.is_hot", req.getIsHot());
        qs.addWhereEqNotEmpty("sp.is_best", req.getIsBest());
        qs.addWhereEqNotEmpty("sp.is_new", req.getIsNew());
        qs.addWhereEqNotEmpty("sp.is_good", req.getIsGood());
        qs.addWhereLikeNotBlank("sp.store_name", req.getName());
        qs.addWhereEqNotEmpty("sp.pink_id", req.getPinkId());
        //qs.addWhereEqNotEmpty("sp.is_integral",req.getIsIntegral());
        qs.addWhereEqNotEmpty("sp.is_hot_integral",req.getIsHotIntegral());
        qs.addWhereGtNotBlank("sp.price", req.getMinPrice());
        qs.addWhereLtNotBlank("sp.price", req.getMaxPrice());

        if(null != req.getCateId()) {
            qs.addWhereParams("exists (select 1 from t_store_product_cate spc where spc.product_id = sp.id and spc.cate_id = ?)", req.getCateId());
        }

        return this.page(qs, StoreProductVo.class);
    }

}
